import axios from 'axios';
import { CONST, API_URL_ROOT, IS_DEVE } from "@/config";
import { appState, appAction } from "@/store/app";
import { ElMessage, ElNotification, ElMessageBox } from "element-plus";
var IsPrompt = false

export const request = function (
  url: string,
  data?: any,
  para?: {
    isUserUrl?: boolean,
    //是否展示错误
    isError?: boolean,
    //
    contentType?: 'json' | 'form',
    //使用自定义的state
    state?: string,
    methods?: 'post' | 'get'
  }): Promise<any> {
  let { isUserUrl = false, isError = true, contentType = "json", state = "", methods = "post" } = para || {};

  let hostUrl = API_URL_ROOT;
  // console.log("url", url);

  let headers: any = {};
  switch (contentType) {
    case "json": {
      headers['Content-Type'] = "application/json";
      break;
    }
    case "form": {
      headers['Content-Type'] = "application/x-www-form-urlencoded";
      break;
    }
  }

  return new Promise((resolve, reject) => {
    let param = {}
    if (methods == "get") {
      param = {
        method: methods,
        url: isUserUrl ? `${url}` : `${hostUrl}${url}`,//&state=${state || appState.pageuuid}
        headers: headers,
        async: false,
        params: Object.assign(data, {
          token: appState.token,
          state: state || appState.pageuuid
        })
      }
    } else {
      param = {
        method: methods,
        url: isUserUrl ? `${url}` : `${hostUrl}${url}`,
        headers: headers,
        data: data,
        params: {
          token: appState.token,
          state: state || appState.pageuuid
        }
      }
    }
    axios(param)
      .then((response) => {
        // console.log("response----", response);
        if (response.status === 200) {
          //说明接口已经正常
          let data: any = response.data;
          if (data.Code == CONST.REQUEST_CODE.getCode("OK")) {
            //接口正常
            resolve(data.Data);
          } else if ([CONST.REQUEST_CODE.getCode("AUTH_INVALID"), CONST.REQUEST_CODE.getCode("TOKEN_INVALID")].indexOf(data.Code) >= 0) {
            // 当前登录用户已失效
            // 这里需要进行特殊处理
            isError && ElMessage.error(data.Msg);
            isError && ElNotification({
              title: '登录失效',
              message: `${data.Msg}`,
              type: 'error',
            })
            if (!IsPrompt) {
              ElMessageBox.alert("由于您长时间未访问，已断开连接，请重新登录!", '提示', {
                confirmButtonText: '确定',
                callback: (action: any) => {
                  IsPrompt = false
                  //置空token
                  appAction.setToken("");
                  //重置登录
                  appAction.setIsAppCreated(false);
                  //然后直接让页面刷新就可以了
                  window.location.reload();
                },
              })
              IsPrompt = true
            }

            reject(data);
          } else {
            //正常报错
            // isError && ElMessage.error(data.Msg);
            isError && ElNotification({
              title: '错误提示',
              message: `${data.Msg}`,
              type: 'error',
            })
            reject(data);
          }
        } else {
          //说明接口出现404等问题
          // ElMessage.error('系统错误:' + response);
          isError && ElNotification({
            title: '系统错误',
            message: `${response}`,
            type: 'error',
          })
          reject(data);
        }

      }).finally(() => {
        appAction.resetPageuuid();
      })
      .catch((error: any) => {
        //属于系统错误
        // isError && ElMessage.error('系统错误:' + error);
        isError && ElNotification({
          title: '系统错误',
          message: `${error}`,
          type: 'error',
        })
        reject()
      })
  })
}
